<template>
  <div class="online-roles" :class="{ 'horizontal-layout': horizontal }">
    <div v-if="!horizontal" class="roles-header">
      <span class="roles-title">在线角色</span>
      <span class="roles-count">{{ onlineRoles.length }}</span>
    </div>

    <div class="roles-list" :class="{ 'horizontal-list': horizontal }">
      <a-tooltip
        v-for="role in onlineRoles"
        :key="role.id"
        :title="role.roleName || '未知角色'"
        :placement="horizontal ? 'bottom' : 'top'"
      >
        <div class="role-avatar-wrapper" @click="handleRoleClick(role)">
          <a-avatar
            :size="horizontal ? 28 : 32"
            :src="role.avatarUrl"
            :style="role.avatarUrl ? {} : { backgroundColor: getRoleColor(role.id), color: 'white' }"
            class="role-avatar"
          >
            {{ (role.roleName || '角色')[0]?.toUpperCase() || 'R' }}
          </a-avatar>
          <div class="online-indicator"></div>
        </div>
      </a-tooltip>

      <!-- 空状态 -->
      <div v-if="onlineRoles.length === 0 && !loading" class="empty-roles">
        <span class="empty-text">{{ horizontal ? '无在线角色' : '暂无在线角色' }}</span>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-roles">
        <a-spin size="small" />
        <span v-if="!horizontal" class="loading-text">加载中...</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import { Codewin } from '@/api/generated/Codewin'
import type { ChatRoomRoleVO } from '@/api/generated/data-contracts'
import { useAuthStore } from '@/stores'

interface Props {
  roomId?: string
  horizontal?: boolean // 新增：是否横向布局
}

const props = withDefaults(defineProps<Props>(), {
  roomId: '',
  horizontal: false
})

// 定义事件
interface Emits {
  rolesUpdated: [roles: ChatRoomRoleVO[]]
  roleClick: [role: ChatRoomRoleVO]
}

const emit = defineEmits<Emits>()

// 响应式状态
const loading = ref(false)
const onlineRoles = ref<ChatRoomRoleVO[]>([])

// 获取认证store
const authStore = useAuthStore()

// 创建API实例，配置认证
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  securityWorker: (securityData) => {
    const token = authStore.token
    return token ? { headers: { Authorization: `Bearer ${token}` } } : {}
  }
})

// 获取角色颜色
const getRoleColor = (roleId?: string) => {
  const colors = [
    '#6366f1', '#8b5cf6', '#ec4899', '#ef4444',
    '#f59e0b', '#10b981', '#06b6d4', '#3b82f6'
  ]
  if (!roleId) return colors[0]
  const index = roleId.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
  return colors[index % colors.length]
}

// 获取在线角色列表
const fetchOnlineRoles = async () => {
  if (!props.roomId) {
    onlineRoles.value = []
    emit('rolesUpdated', [])
    return
  }

  loading.value = true
  try {
    const response = await api.getChatRoomRoles(props.roomId)
    if (response.data?.code === 0 && response.data?.data) {
      // 这里假设所有获取到的角色都是在线的
      // 实际项目中可能需要根据角色状态字段来过滤
      onlineRoles.value = response.data.data
      emit('rolesUpdated', response.data.data)
    } else {
      console.warn('获取角色列表失败:', response.data?.message)
      onlineRoles.value = []
      emit('rolesUpdated', [])
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    onlineRoles.value = []
    emit('rolesUpdated', [])
  } finally {
    loading.value = false
  }
}

// 监听roomId变化
watch(() => props.roomId, async (newRoomId) => {
  if (newRoomId) {
    await fetchOnlineRoles()
  } else {
    onlineRoles.value = []
  }
}, { immediate: true })

// 组件挂载时获取数据
onMounted(() => {
  if (props.roomId) {
    fetchOnlineRoles()
  }
})

// 暴露刷新方法给父组件
defineExpose({
  refresh: fetchOnlineRoles
})

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return '未知'

  const date = new Date(dateStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  // 小于1分钟
  if (diff < 60000) return '刚刚'
  // 小于1小时
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  // 小于1天
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  // 小于7天
  if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`

  // 超过7天显示具体日期
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  })
}

// 处理角色点击
const handleRoleClick = (role: ChatRoomRoleVO) => {
  emit('roleClick', role)
}
</script>

<style scoped>
.online-roles {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
}

.roles-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.roles-title {
  font-size: 14px;
  font-weight: 500;
  color: #262626;
}

.roles-count {
  font-size: 12px;
  color: #8c8c8c;
  background: #f5f5f5;
  padding: 2px 8px;
  border-radius: 10px;
}

.roles-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

/* 横向布局样式 */
.horizontal-layout {
  padding: 0;
  margin-left: 16px;
}

.horizontal-list {
  gap: 6px;
  flex-wrap: nowrap;
  overflow-x: auto;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.horizontal-list::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}

.horizontal-layout .empty-roles {
  padding: 0;
  min-width: 80px;
}

.horizontal-layout .loading-roles {
  padding: 0;
  min-width: 60px;
  justify-content: flex-start;
}

.role-avatar-wrapper {
  position: relative;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.role-avatar-wrapper:hover {
  transform: scale(1.1);
}

.role-avatar {
  border: 2px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.online-indicator {
  position: absolute;
  bottom: -2px;
  right: -2px;
  width: 10px;
  height: 10px;
  background: #52c41a;
  border: 2px solid #fff;
  border-radius: 50%;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
}

.empty-roles {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 20px 0;
}

.empty-text {
  font-size: 12px;
  color: #bfbfbf;
}

.loading-roles {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
  justify-content: center;
  padding: 20px 0;
}

.loading-text {
  font-size: 12px;
  color: #8c8c8c;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .online-roles {
    padding: 12px;
  }

  .role-avatar {
    width: 28px !important;
    height: 28px !important;
  }

  .online-indicator {
    width: 8px;
    height: 8px;
  }
}

/* 动画效果 */
.role-avatar-wrapper {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.8);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

/* Tooltip 样式优化 */
:deep(.ant-tooltip-inner) {
  background: rgba(0, 0, 0, 0.85);
  border-radius: 6px;
  font-size: 12px;
}

:deep(.ant-tooltip-arrow::before) {
  background: rgba(0, 0, 0, 0.85);
}
</style>
